package cn.it.shop.lucene;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.apache.lucene.search.Query;
import org.apache.lucene.search.highlight.Formatter;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.Scorer;
import org.apache.lucene.search.highlight.SimpleFragmenter;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.springframework.stereotype.Component;

/*
 * 用来给字段设置高量效果的工具类
 * */
@Component("highlighterUtil")
public class HighlighterUtil {
	
	@Resource
	private Configuraction configuraction=null;

	// 设置高亮的格式,此配置后面要放到properties文件中
	private Formatter formatter = null;
	
	@PostConstruct
	public void init(){
		formatter=new SimpleHTMLFormatter("<font color='red'>", "</font>");
	}
	
	// 此方法返回高亮后的结果
	public String setHighlighterText(Query query,String text,int length){
		// 设置高亮的查询关键字, 必须要query对象, 因为关键字也需要分词
		Scorer scorer = new QueryScorer(query);
		Highlighter highlighter = new Highlighter(formatter, scorer);
		// 设置高亮后保存的字符串长度, 不同的字段,保存的长度应该不同 name 20 remark 300
		highlighter.setTextFragmenter(new SimpleFragmenter(length));
		// 对某个字段进行高亮,被高亮的字段也要分词才能和关键字匹配,返回是高亮后的字符串
		String result;
		try {
			System.out.println(highlighter);
			result = highlighter.getBestFragment(configuraction.getAnalyzer(), null, text);
			// 说明在当前field字段没有匹配到关键字, 那么也应该显示原字段的值
			if(result==null){
				// 如果大于最大长度先截取在给result变量
				if(text.length()>length){
					result=text.substring(0,length);
				}else{
					result=text;
				}
			}
			return result;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		
	}
}
